package com.xiaoqiudong.forum.service.impl;

import com.xiaoqiudong.forum.common.AppResult;
import com.xiaoqiudong.forum.common.ResultCode;
import com.xiaoqiudong.forum.common.utils.StringUtils;
import com.xiaoqiudong.forum.dao.ArticleMapper;
import com.xiaoqiudong.forum.exception.ApplicationException;
import com.xiaoqiudong.forum.model.Article;
import com.xiaoqiudong.forum.model.Board;
import com.xiaoqiudong.forum.model.User;
import com.xiaoqiudong.forum.service.IArticleService;
import com.xiaoqiudong.forum.service.IBoardService;
import com.xiaoqiudong.forum.service.IUserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Descroption
 * User:dell
 * Date:2025-08-26
 * Time:9:23
 */
@Service
@Slf4j
public class ArticleServiceImpl implements IArticleService {
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private IUserService userService;
    @Resource
    private IBoardService boardService;
    @Override
    public void create(Article article) {
        //非空校验
        if (article == null || article.getUserId()== null||article.getBoardId() == null
            || StringUtils.isEmpty(article.getContent())
            || StringUtils.isEmpty(article.getTitle())){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //设置默认值
        article.setReplyCount(0);//回复数
        article.setVisitCount(0);//访问数
        article.setLikeCount(0);//点赞数
        article.setState((byte) 0);
        article.setDeleteState((byte) 0);
        Date date = new Date();
        article.setCreateTime(date);
        article.setUpdateTime(date);

        //写入数据库
        int articleRow = articleMapper.insertSelective(article);
        if (articleRow != 1){
            log.warn(ResultCode.FAILED.toString() +",发帖失败， user id = "+article.getUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        // 获取用户信息
        User user = userService.selectById(article.getUserId());
        // 没有找到指定的用户信息
        if (user == null) {
            log.warn(ResultCode.FAILED_CREATE.toString() + ", 发贴失败, user id = " + article.getUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        // 更新用户的发贴数
        userService.addOneArticleCountById(user.getId());
        Board board = boardService.selectById(article.getBoardId());
        if (board == null){
            log.warn(ResultCode.FAILED_CREATE.toString() +"，发帖失败， board id = "+article.getBoardId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_CREATE));
        }
        boardService.addOneArticleCountById(board.getId());

        //发帖成功
        log.info(ResultCode.SUCCESS.toString()+"，发帖成功，user id = "+article.getUserId()
        + "board id = "+ article.getBoardId());

    }

    @Override
    public List<Article> selectAll() {
        List<Article> articles = articleMapper.selectAll();
        return articles;
    }

    @Override
    public List<Article> selectAllByBoardId(Long boardId) {
        if (boardId == null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Board board = boardService.selectById(boardId);
        if (board == null){
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString()+"boardId="+boardId );
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_BOARD_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectAllByBoardId(boardId);
        return articles;
    }

    @Override
    public Article selectDetailById(Long id) {
        if (id == null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+"id= "+id);
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectDetailById(id);
        if (article == null){
            log.info(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //更新贴子访问数
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setVisitCount(article.getVisitCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        //返回实时访问数
        article.setVisitCount(article.getVisitCount()+1);
        return article;
    }

    @Override
    public Article selectById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString()+"id = "+id);
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        return article;
    }

    @Override
    public void modify(Long id, String title, String content) {
        if(id == null||id <= 0 || StringUtils.isEmpty(title) || StringUtils.isEmpty(content)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article updateArticle = new Article();
        updateArticle.setId(id);
        updateArticle.setTitle(title);
        updateArticle.setContent(content);
        updateArticle.setUpdateTime(new Date());

        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1){
            //更新失败
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void thumbsUpById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setLikeCount(article.getLikeCount()+1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void deleteById(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setDeleteState((byte) 1);
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
        userService.subOneArticleCountById(article.getUserId());
        boardService.subOneArticleCountById(article.getBoardId());
        log.info("删除帖子成功, article id = " + article.getId() + ", user id = " + article.getUserId() + ".");
    }

    @Override
    public void addOneReplyCount(Long id) {
        if (id == null || id <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        Article article = articleMapper.selectByPrimaryKey(id);
        if (article == null || article.getDeleteState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        //帖子封贴
        if (article.getState() == 1){
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_ARTICLE_BANNED));
        }
        Article updateArticle = new Article();
        updateArticle.setId(article.getId());
        updateArticle.setReplyCount(article.getReplyCount()+1);
        updateArticle.setUpdateTime(new Date());
        int row = articleMapper.updateByPrimaryKeySelective(updateArticle);
        if (row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public List<Article> selectAllByUserId(Long userId) {
        if (userId == null || userId <= 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userService.selectById(userId);
        //检验用户是否存在
        if (user == null || user.getDeleteState() == 1 ){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        List<Article> articles = articleMapper.selectAllByUserId(userId);
        return articles;

    }
}
